package in.co.codedoc.cg.velocity;

import java.io.IOException;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.TemplateInitException;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;

@CGDirective
public abstract class CGBlockDirective extends Directive
{
	protected CGBlockDirective(String ... parameters)
	{
		this.parameters = parameters;
		this.numArguments = parameters.length;
	}
	
	@Override
	public int getType()
	{
		return BLOCK;
	}
	
	@Override
	public void init(RuntimeServices rs, InternalContextAdapter context, Node node) 
		throws TemplateInitException
	{
		super.init(rs, context, node);
		
		if(node.jjtGetNumChildren() < numArguments)
		{
			throw new TemplateInitException( getName() + " accepts " + numArguments + " arguments" + getParameterNames() + ".",context.getCurrentTemplateName(),
	                getLine(),getColumn());
		}
	}

	private String getParameterNames()
	{
		StringBuffer buffer = new StringBuffer();
		
		if(parameters.length > 0)
		{
			int index = 0;
			buffer.append('(');
			for(String parameter:parameters)
			{
				if(index > 0)
				{
					buffer.append(",");
				}
				buffer.append('\'');
				buffer.append(parameter);
				buffer.append('\'');
				index++;
			}
			buffer.append(')');
		}
		
		return buffer.toString();
	}

	protected static String getArgument(InternalContextAdapter context,Node node,int parameter) 
		throws IOException
	{
		if(!(node.jjtGetNumChildren() > parameter))
		{
			return null;
		}
		
		Object value = node.jjtGetChild(parameter).value(context).toString(); 
		
		return value != null ? value.toString() : "";
	}
	
	private int numArguments;
	private String[] parameters;

}
